package LC;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/search-for-a-range/description/
 * Given an array of integers sorted in ascending order,
 * find the starting and ending position of a given target value.
 * Your algorithm's runtime complexity must be in the order of O(log n).
 * If the target is not found in the array, return [-1, -1].
 * For example,
 * Given [5, 7, 7, 8, 8, 10] and target value 8,
 * return [3, 4].
 */
public class LC_034_SearchforaRange_BinarySearch_Array {
    public static void main(String[] args) {
        int[] a = {1, 2, 2, 3, 3, 3, 4, 4};
        int target = 3;
        int[] idx = Solution.searchRange(a, target);
        System.out.println(Arrays.toString(idx));
    }

    static class Solution {
        static int[] searchRange(int[] nums, int target) {
            int[] result = {-1, -1};
            int index = searchRightIndex(nums, 0, nums.length - 1, target);

            if (index < 0 || nums[index] != target)
                return result;

            result[0] = searchLeftIndex(nums, 0, index, target);
            result[1] = index;
            return result;
        }

        private static int searchRightIndex(int[] nums, int left, int right, int target) {
            while (left <= right) {
                int mid = (left + right) >> 1;
                if (nums[mid] > target) right = mid - 1;
                else left = mid + 1;
            }
            System.out.println(left + "     " + right);
            return right;
        }

        private static int searchLeftIndex(int[] nums, int left, int right, int target) {
            while (left <= right) {
                int mid = (left + right) >> 1;
                if (nums[mid] < target) left = mid + 1;
                else right = mid - 1;
            }
            return left;
        }
    }

    static class Solution_2 {
        static public int[] searchRange(int[] nums, int target) {
            int st = -1;
            int en = -1;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == target) {
                    if (nums[i] == target) {
                        st = i;
                        break;
                    }
                }
            }
            for (int i = nums.length - 1; i >= 0; i--) {
                if (nums[i] == target) {
                    en = i;
                    break;
                }
            }
            return new int[]{st, en};
        }
    }
}
